package com.doge.walknovel.utils

import androidx.fragment.app.FragmentActivity
import java.util.*

object Activities {
    private val list: MutableList<FragmentActivity> = LinkedList()

    val top: FragmentActivity? get() = list.lastOrNull()

    fun contains(activityClazz: Class<*>): Boolean {
        for (activity in list) {
            if (!activity.isFinishing) {
                if (activity.javaClass.simpleName == activityClazz.simpleName) {
                    return true
                }
            }
        }
        return false
    }

    fun remove(activity: FragmentActivity) {
        require(isMainThread())
        if (list.contains(activity)) {
            list.remove(activity)
        }

    }

    fun add(activity: FragmentActivity) {
        require(isMainThread())
        if (!list.contains(activity)) {
            list.add(activity)
        }
    }

    fun finishAll() {
        require(isMainThread())
        list.forEach { it.finish() }
        list.clear()
    }

    fun finish(activityClazz: Class<*>) {
        list.forEach {
            if (!it.isFinishing && it.javaClass.simpleName == activityClazz.simpleName) {
                it.finish()
            }
        }
    }
}